package cz.data.common.elastic;

import cz.data.common.support.db.DbProperty;
import cz.data.common.utils.ThrowableUtil;
import org.elasticsearch.client.RestHighLevelClient;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

public class CacheClientBean {
    private static final Map<String, RestHighLevelClient> CACHE_CLIENT = new ConcurrentHashMap<>();

    public static void shutdown() {
        for (Map.Entry<String, RestHighLevelClient> entry : CACHE_CLIENT.entrySet()) {
            RestHighLevelClient highLevelClient = entry.getValue();
            ThrowableUtil.throwable(highLevelClient::close);
        }
    }

    public static void invalid(String key) {
        RestHighLevelClient client = CACHE_CLIENT.remove(key);
        if (Objects.nonNull(client)) {
            ThrowableUtil.throwable(client::close);
        }
    }

    public static RestHighLevelClient createClient(DbProperty property) {
        String key = property.getId();
        RestHighLevelClient client = CACHE_CLIENT.get(key);
        if (Objects.isNull(client)) {
            synchronized (key) {
                client = CACHE_CLIENT.get(key);
                if (Objects.isNull(client)) {
                    client = ElasticSearchUtils.createClient(property);
                    CACHE_CLIENT.put(key, client);
                }
            }
        }
        return client;
    }
}
